<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition License
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magentocommerce.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Customer
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://www.magentocommerce.com/license/enterprise-edition
 */

/**
 * API2 class for customer (customer)
 *
 * @category   Mage
 * @package    Mage_Customer
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Silk_Mapi_Model_Api2_Account_Rest_Guest_V1 extends Silk_Mapi_Model_Api2_Account_Rest
{
    /**
     * Retrieve information about customer
     *
     * @throws Mage_Api2_Exception
     * @return array
     */
    protected function _retrieve()
    {
        $action = $this->getRequest()->getParam('action');

        if ($action == "checktoken") {
            $token = Mage::getModel('mapi/token')->loadByToken($this->getRequest()->getParam('token'));
            //echo get_class($token);
            if ($token && $token->getId()) {
                $customer = $this->_loadCustomerById($token->getCustomerId());
                $result = array(
                    'customer_id' => $customer->getId(),
                    'firstname' => $customer->getFirstname(),
                    'lastname' => $customer->getLastname(),
                    'username' => $customer->getUsername(),
                    'email' => $customer->getEmail(),
                    'access_token' => $token->getToken(),
                    'access_token_secret' => $token->getTokenSecret()
                );
                return $result;
            } else {
                $this->_critical(self::RESOURCE_NOT_FOUND);
            }
        }
        $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED, Mage_Api2_Model_Server::HTTP_FORBIDDEN);
    }

    /**
     * Retrieve collection with only current customer instance
     *
     * @return Mage_Customer_Model_Resource_Customer_Collection
     */
    protected function _getCollectionForRetrieve()
    {
        return parent::_getCollectionForRetrieve()->addAttributeToFilter('entity_id', $this->getApiUser()->getUserId());
    }

    /**
     * Update customer
     *
     * @param array $data
     * @return string|void
     * @throws Mage_Api2_Exception
     */
    protected function _update(array $data)
    {
        if ($mobile = $this->getParam('mobile')) {
            if (!preg_match("/^[1][34578][0-9]{9}$/", $mobile)) {
                $this->_critical('手机号码格式不正确！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_MOBILE_FORMAT_ERROR);
            }

            /** @var Mage_Customer_Model_Customer $customerModel */
            $customerModel = Mage::getModel('customer/customer');
            $email = "{$mobile}@hahahui.cn";
            $collection = $customerModel->getCollection()->addAttributeToFilter('email', array('eq' => $email));
            $item = $collection->getFirstItem();

            if (!$item || !$item->getId()) {
                $this->_critical('当前用户不存在！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_NOT_FOUND);
            }

            $customer = $customerModel
                ->setWebsiteId($item->getWebsiteId())
                ->loadByEmail($email);

            $newPassword = $this->getParam('new_password');
            $confirmation = $this->getParam('confirmation');
            if (strlen($newPassword) < 6 || strlen($newPassword) > 20)
                $this->_critical("请输入6~20位的密码!", Mage_Api2_Model_Resource::ERROR_CUSTOMER_PASSWORD_LENGTH);

            if ($newPassword !== $confirmation)
                $this->_critical("两次输入的密码不相同!", Mage_Api2_Model_Resource::ERROR_CUSTOMER_PASSWORD_NOT_MATCH);

            $cache = Mage::app()->getCache();
            $captchaSaved = $cache->load('CAPTCHA_'.$mobile);
            if (!$captchaSaved)
                $this->_critical("请先获取验证码!", Mage_Api2_Model_Resource::ERROR_CAPTCHA_NEED);

            if ($this->getParam('captcha') !== $captchaSaved) {
                $attemptTimes = $cache->load('CAPTCHA_TIMES_'.$mobile);

                if (!$attemptTimes) $attemptTimes = 1;
                if ($attemptTimes >= 3) {
                    $cache->remove('CAPTCHA_'.$mobile);
                    $cache->remove('CAPTCHA_TIMES_'.$mobile);
                    $this->_critical("已经输错了3次验证码，请重新获取!", Mage_Api2_Model_Resource::ERROR_CAPTCHA_NEED_RESEND);
                }
                $cache->save((string)($attemptTimes + 1), 'CAPTCHA_TIMES_'.$mobile, array('QSLB_CAPTCHA'), 600);
                $this->_critical("验证码错误!", Mage_Api2_Model_Resource::ERROR_CAPTCHA_NOT_MATCH);
            }

            try {
                $customer->setPassword($newPassword);
                $customer->save();
                $cache->remove('CAPTCHA_'.$mobile);
                $cache->remove('CAPTCHA_TIMES_'.$mobile);
            } catch (Exception $e) {
                $this->_critical($e->getMessage(), Mage_Api2_Model_Resource::ERROR_ACCOUNT_UNKNOWN_ERROR);
            }

            return array();
        } else {
            $this->_critical('请输入手机号码！', Mage_Api2_Model_Resource::ERROR_ACCOUNT_MOBILE_EMPTY);
        }
    }

    /**
     * Update customers
     *
     * @param array $data
     * @throws Mage_Api2_Exception
     */
    protected function _multiUpdate(array $data)
    {
        $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED, Mage_Api2_Model_Server::HTTP_FORBIDDEN);
    }

    /**
     * @throws Exception
     * @throws Mage_Api2_Exception
     */
    protected function _retrieveCollection()
    {
        $this->_critical(self::RESOURCE_METHOD_NOT_ALLOWED, Mage_Api2_Model_Server::HTTP_FORBIDDEN);
    }
}
